#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

int g_num = 50;
pthread_mutex_t g_lock;  //全局互斥锁

void* my_start(void* arg)
{

    while(1){
        pthread_mutex_lock(&g_lock);    
        //pthread_mutex_trylock()   pthrea_mutex_timedlock
        if(g_num <= 0){
       pthread_mutex_unlock(&g_lock);
            break;
        }
        printf("i am thread : %p; num is %d\n", pthread_self(), g_num);
        g_num--;

        pthread_mutex_unlock(&g_lock);
        sleep(1);
     }
    
    return NULL;
}

int main()
{
    //初始化互斥锁
    pthread_mutex_init(&g_lock, NULL);

    //1.创建线程
    //  两个工作线程修改全局变量
    pthread_t tid[2];
    int i;
    for(i = 0; i < 2; i++){
       int ret = pthread_create(&tid[i], NULL, my_start, NULL);
       if(ret < 0){
           perror("pthread_create\n");
           return 0;
       }
    }

    //主线程不退出
    for(i = 0; i < 2; ++i){
        pthread_join(tid[i], NULL);
    }

    pthread_mutex_destroy(&g_lock);  //销毁
    return 0;
}
